package com.stenio.fancat.service.user;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.common.errorCode.ErrorCode;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.candy.Candy;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipCandy;
import com.stenio.fancat.domain.user.UserRelationshipFomId;
import com.stenio.fancat.domain.user.UserRelationshipName;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.user.UserKinsfolkForm;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.candy.CandyMapper;
import com.stenio.fancat.mapper.user.*;
import com.stenio.fancat.service.wx.WxPushServiceQcl;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.EmptyUtil;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.vo.BabyRelationshipVO;
import com.stenio.fancat.vo.UserRelationshipVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * baby关系信息类
 */
@Service
public class UserRelationshipService extends ServiceImpl<UserRelationshipMapper, UserRelationship> {

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private UserRelationshipCandyMapper userRelationshipCandyMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private BabyAccountMapper babyMapper;

    @Autowired
    private UserRelationshipLogMapper userRelationshipLogMapper;

    @Autowired
    private UserRelationshipNameMapper userRelationshipNameMapper;

    @Autowired
    private UserRelationshipFomIdMapper userRelationshipFomIdMapper;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    @Autowired
    private CandyMapper candyMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${key}")
    private String babyKey;

    @Value("${kinsfolkListInvite}")
    private String key;

    @Value("${listKey}")
    private String listKey;

    @Value("templateNewPerson")
    private String templateNewPerson;


    /**
     * 邀请亲人 （和登录的逻辑一样）
     * @param userKinsfolkForm
     * @return
     */
    @Transactional
    public Integer inviteKinsfolk(UserKinsfolkForm userKinsfolkForm) throws FanCatException {
        if(EmptyUtil.isEmpty(userKinsfolkForm)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        Integer number = 0;
        //先查询该baby对应的user关系  ----->  先查询有没有邀请过
        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(userKinsfolkForm.getKinsfolkUserId(),userKinsfolkForm.getBabyId());
        UserRelationship user = userRelationshipMapper.selectUserInfoById(userKinsfolkForm.getKinsfolkUserId());
        if (EmptyUtil.isNotEmpty(babyRelationship)){
            throw new FanCatException("已经和宝宝有关联了",ErrorCode.hasrelationOfKinsfolk);
        }
        //修改关系
        BabyRelationship babys = new BabyRelationship();
        Date date = new Date();
        babys.setBabyId(userKinsfolkForm.getBabyId());
        babys.setUserId(userKinsfolkForm.getKinsfolkUserId());
        babys.setInviteUserId(userKinsfolkForm.getUserId());
        babys.setType(1);
        babys.setState(0);
        babys.setRelationship(userKinsfolkForm.getRelationship());
        babys.setCreateTime(date);
        babys.setUpdateTime(date);
        babyRelationshipMapper.insert(babys);

        //创建candy表 Log表不用创建
        UserRelationshipCandy userRelationshipCandy = new UserRelationshipCandy();
        userRelationshipCandy.setCreateTime(date);
        userRelationshipCandy.setUpdateTime(date);
        userRelationshipCandy.setReduceCandy(0);
        userRelationshipCandy.setIncreaseCandy(0);
        userRelationshipCandy.setUserId(userKinsfolkForm.getKinsfolkUserId());
        userRelationshipCandy.setBabyId(userKinsfolkForm.getBabyId());
        userRelationshipCandyMapper.insert(userRelationshipCandy);

        //邀请成功后推送微信模板消息
        String userId = userKinsfolkForm.getUserId();
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(userId);
        String[] arr = new String[5];
        arr[0] = user.getName()+"加入宝宝圈";
        arr[1] = "亲人圈";
        arr[2] = DateUtil.format(date,"yyyy-MM-dd HH:mm:ss");
        UserRelationshipFomId userRelationshipFomId = userRelationshipFomIdMapper.selectFormIdByUid(userId);
        if(null != userRelationshipFomId){
            String formId = userRelationshipFomIdMapper.selectFormIdByUid(userId).getFormId();
            //推送通知
            wxPushServiceQcl.pushOneUser(userRelationship.getOpenId(),formId,"zT81v_RBlI92CY5fwQgKN7qXDU-aVvRHq3z9cGlN4ks",arr,userKinsfolkForm.getPage());
            //修改这个formid的状态
            userRelationshipFomIdMapper.modifyFormIdByUid(userId,formId);
        }

        //操作Redis
        redisUtil.del(key+userKinsfolkForm.getBabyId(),listKey+userKinsfolkForm.getBabyId());

        return number;
    }

    /**
     * 被邀请页面的API
     * @param userId
     * @return
     */
    public BabyRelationshipVO invitedPage(String userId,String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId) || EmptyUtil.isEmpty(babyId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        BabyRelationshipVO babyRelationshipVO = new BabyRelationshipVO();
        //查询baby存在的关系传给前端展示，已经有的不能再次选择
        List<BabyRelationship> babyRelationshipList = babyRelationshipMapper.selectRelationship(babyId);
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<babyRelationshipList.size();i++){
            list.add(babyRelationshipList.get(i).getRelationship());
        }
        //查询数据库中所有的关系名称
        List<UserRelationshipName> listnames = userRelationshipNameMapper.selectAllNames();
        babyRelationshipVO.setUserRelationshipName(listnames);

        babyRelationshipVO.setSelectedNames(list);
        return babyRelationshipVO;
    }

    /**
     * 查询邀请的亲人的列表的页面 --------包含baby的昵称（已邀请的亲人）
     * @param userId
     * @return
     */
    public Map<String,Object> inviteUserList(String userId,String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId) || EmptyUtil.isEmpty(babyId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }

//        //判断Redis中是否含有key
//        if(EmptyUtil.isNotEmpty(redisUtil.get(key+babyId))){
//            return (Map<String, Object>) redisUtil.get(key+babyId);
//        }

        //创建map容器
        Map<String,Object> map = new HashMap<>();
        //封装babyName
        String babyName = babyMapper.selectByBid(babyId).getNickName();
        map.put("babyName",babyName);
        List<BabyRelationship> list = babyRelationshipMapper.selectList(userId);
        //创建userVO容器
        List<UserRelationshipVO> voList = new ArrayList<>();
        if(EmptyUtil.isNotEmpty(list)){
            for(int i = 0;i<list.size();i++){
                UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
                UserRelationshipName userRelationshipName = new UserRelationshipName();
                userRelationshipName.setRelationship(list.get(i).getRelationship());
                String rname = userRelationshipNameMapper.selectOne(userRelationshipName).getRelationshipName();
                userRelationshipVO.setRelationship(list.get(i).getRelationship());
                userRelationshipVO.setUserId(list.get(i).getUserId());
                userRelationshipVO.setRelationshipName(rname);
                UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(list.get(i).getUserId());
                userRelationshipVO.setName(userRelationship.getName());
                userRelationshipVO.setImage(userRelationship.getIcon());
                userRelationshipVO.setState(list.get(i).getState());//0,未领取 1,为已经领取
                voList.add(userRelationshipVO);
            }
        }

        //封装爸爸妈妈的信息
        List<BabyRelationship> babyRelationshipList = babyRelationshipMapper.selectRelationship(babyId);
        List<UserRelationshipVO> voList2 = new ArrayList<>();
        for(int i = 0;i<babyRelationshipList.size();i++){
            if(babyRelationshipList.get(i).getRelationship() == 1 || babyRelationshipList.get(i).getRelationship() == 2){
                UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
                UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(babyRelationshipList.get(i).getUserId());
                UserRelationshipName userRelationshipName = new UserRelationshipName();
                userRelationshipName.setRelationship(babyRelationshipList.get(i).getRelationship());
                String rname2 = userRelationshipNameMapper.selectOne(userRelationshipName).getRelationshipName();
                userRelationshipVO.setRelationship(babyRelationshipList.get(i).getRelationship());
                userRelationshipVO.setUserId(babyRelationshipList.get(i).getUserId());
                userRelationshipVO.setRelationshipName(rname2);
                userRelationshipVO.setName(userRelationship.getName());
                userRelationshipVO.setImage(userRelationship.getIcon());
                userRelationshipVO.setState(babyRelationshipList.get(i).getState());//0,未领取 1,为已经领取
                voList2.add(userRelationshipVO);
            }
        }


        //封装已经邀请的亲人列表
        map.put("userList",voList);
        map.put("fatherOrMother",voList2);
//        //存放Redis中
//        redisUtil.set(key+babyId,map);

        return map;
    }

    /**
     * 查询该baby下所有的亲人的列表
     * @param userId
     * @return
     * @throws FanCatException
     */
    public List<UserRelationshipVO> allKinsfolk(String userId,String babyId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId)){
            throw new FanCatException("参数为空",ErrorCode.parameters);
        }

        if(EmptyUtil.isEmpty(babyRelationshipMapper.selectBabyByUid(userId))){
            throw new FanCatException("该用户没有绑定任何baby",ErrorCode.addBaby);
        }

        //创建封装的容器
        List<UserRelationshipVO> userRelationshipVOList = new ArrayList<>();

        //查询babyI和userId
        List<BabyRelationship> list = babyRelationshipMapper.selectUserListByBabyId(babyId);
        list.stream().forEach(baby -> {
            UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
            userRelationshipVO.setRelationship(baby.getRelationship());
            userRelationshipVO.setUserId(baby.getUserId());
            UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(baby.getUserId());
            BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUidAndBid(baby.getUserId(),baby.getBabyId());
            userRelationshipVO.setImage(userRelationship.getIcon());
            userRelationshipVO.setName(userRelationship.getName());
            userRelationshipVO.setRelationshipName(userRelationshipNameMapper.selectName(babyRelationship.getRelationship()).getRelationshipName());
            userRelationshipVO.setIncreaseCandy(userRelationshipCandyMapper.selectAddCandyById(babyRelationship.getUserId(),babyRelationship.getBabyId()).getIncreaseCandy());

            userRelationshipVOList.add(userRelationshipVO);
        });

        return userRelationshipVOList;
    }

    /**
     * 领取糖果币（candy）  如果领完变成已领取
     * @param userId
     * @return
     */
    @Transactional
    public UserRelationshipVO getUserCandy(String userId,String babyId,String inviteUserId) throws FanCatException {
        if(EmptyUtil.isEmpty(userId)){
            throw new FanCatException("参数异常",ErrorCode.parameters);
        }
        UserRelationshipVO userRelationshipVO = new UserRelationshipVO();
        Integer candyFir = babyMapper.selectByBid(babyId).getSurplusCandy();
        //创建获取糖果币的示例
        Candy candy = candyMapper.selectCandy();
        userRelationshipLogMapper.modifyCandy(candy.getInviteUserCandy(),inviteUserId,candyFir,babyId);
        userRelationshipCandyMapper.modifyCandy(candy.getInviteUserCandy(),inviteUserId,babyId);
        babyMapper.modifyCandy(candy.getInviteUserCandy(),babyId);
        //修改领取candy的状态为1

        babyRelationshipMapper.modifyRelationshipState(userId,inviteUserId);

        //查询是否修改了candy领取状态
        BabyRelationship babyRelationship = babyRelationshipMapper.selectIfmodifyState(userId,inviteUserId);
        userRelationshipVO.setState(babyRelationship.getState());

        //操作Redis
        Set<String> keys = redisTemplate.keys(babyKey + babyId + "*");
        redisTemplate.delete(keys);
        redisUtil.del(key+babyId,listKey+babyId);

        return userRelationshipVO;

    }

}
